<template>
	<view>
		<canvas v-if="showCanvas" :style="{height: pupopHeight + 'px',width: pupopWidth + 'px'}" canvas-id="myCanvas"></canvas>
		<view>
			  <view class="background"></view>
			  <view class="title flex align-center justify-between"style="width: 100%;color: #ffffff;">
				  <uni-icons style="flex:1;position: relative;left: 30rpx;" type="left" size="17" color="#ffffff" @click="goBack()"></uni-icons>
				  <view style="flex:1;height: 50rpx;font-size: 34rpx;line-height: 50rpx;letter-spacing: 5rpx; text-align: center;">我要传递</view>
				  <view style="flex:1"></view>
			  </view>
			  <image class="logo" mode="aspectFill" src="@/static/images/logo.png" ></image>
			  <image class="avatar" mode="aspectFill" :src="user.avatar"></image>
			  <view class="content">
				  <image class="image" mode="aspectFill" :src="info.imageUrl"></image>
				  <view class="item-content">
					<view class="item-box-title">
						{{info.title}}
					</view>
					<view class="item-box-content">
						{{info.content}}
					</view>
				  </view>
			  </view>
			  <view class="button-box">
				  <button class="button left" open-type="share">分享到微信</button>
				  <button class="button right" @click="showShare1()">分享到朋友圈</button>
			  </view>
			  <view class="share-box" @click="showShare = false" v-if="showShare">
				  <image class="share-card" @click.native.stop :src="posterImg" mode="aspectFill">
				  </image>
				  <view class="share-button-box" v-if="!showCanvas" @click.native.stop="saveToLocal()">
				  		<button class="button" >保存图片分享到朋友圈</button>
				  </view>
			  </view>
		</view>
	</view>
</template>

<script>
	
import config from '@/config'
  
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { toast} from '@/utils/common'
import { getActivityInfo,getQrCode,share } from '@/api/system/pubulic'
  export default {
    data() {
      return {
		  baseUrl:config.baseUrl,
        params: {},
        showShare:false,
		showCanvas:false,
		info:{
			id:'',
			title:'',
		},
		user:{
			userId : storage.get(constant.id),
			name : storage.get(constant.name),
			avatar : storage.get(constant.avatar)
		},
		pupopWidth:690,
		pupopHeight:1050,
		//一定要注意像素密度的问题，这里使用的固定数值
		pixelRatio:3,//屏幕像数密度
		inviteQR:"",//动态二维码
		posterImg:'',//最后生成的海报
      }
    },
	mounted(){
			this.pupopWidth = this.pupopWidth*this.pixelRatio
			this.pupopHeight = this.pupopHeight*this.pixelRatio
			console.log("屏幕像素密度",this.pixelRatio,this.pupopWidth,this.pupopHeight)
	    },
    props: {
      src: {
        type: [String],
        default: null
      }
    },
	onShareAppMessage() {
		const promise = new Promise(resolve => {
			share({activityId:this.info.id}).then()
		})
		return {
			title: this.info.title||"济南中科+",
			path:'pages/detail/index?id='+this.info.id+(this.user.userId?'&u='+this.user.userId:''),
			promise
		}
	},
	onShareTimeline() {
		const promise = new Promise(resolve => {
			share({activityId:this.info.id}).then()
		})
		return {
			title: this.info.title||"济南中科+",
			path:'pages/detail/index?id='+this.info.id+(this.user.userId?'&u='+this.user.userId:''),
			promise
		}
	},
    onLoad(event) {
		console.log(event)
      this.params = event
      if(event.id){
		  getActivityInfo({id:event.id}).then((res)=>{
			  this.info = res.data
		  })
	  }
    },
	methods:{
		goBack(){
			uni.navigateBack();
		},
		showShare1(){
			this.showShare = true;
			this.createPoster();
		},
		//生成海报--微信端
			createPoster(){
				this.showCanvas = true;
				uni.showLoading()
			    let _this = this
				_this.headImg = this.user.avatar//去本地缓存获取头像
				const canvasId = "myCanvas"
				let  ctx = uni.createCanvasContext(canvasId,_this) // 自定义组件中 一定要传this ，这里一开始没加，困惑很久，一定要写一下
				// 填充背景
				ctx.setFillStyle('#FFFFFF')
				ctx.fillRect(0,0,_this.pupopWidth,_this.pupopHeight);
				ctx.save()
				
				//生成banner图
				uni.getImageInfo({
						src: _this.info.imageUrl,//这里的banner是展示的商品图
						success(image) {
						let bannerW = 690 * _this.pixelRatio
						let bannerH = 640 * _this.pixelRatio
						let bannerX = 0 * _this.pixelRatio
						let bannerY = 0 * _this.pixelRatio
						// 将banner到画布上
						ctx.drawImage(image.path, bannerX, bannerY, bannerW, bannerH)
						ctx.restore()
						ctx.save()
						
						
						
						//这里会处理多行显示文字，超出显示省略号的效果
						let bannerTextX = 20 * _this.pixelRatio
						let bannerTextY = bannerH + 60 * _this.pixelRatio   //这里的y轴起始值是顶上的距离还要特意加上文字的行高
						let chr = _this.info.title.split("");//这个方法是将一个字符串分割成字符串数组
						let temp = "";
						let row = [];
						ctx.setFontSize(42*_this.pixelRatio)
						ctx.setFillStyle(4)
						ctx.setFillStyle("#000000")
						for (var a = 0; a < chr.length; a++) {
						    if (ctx.measureText(temp).width < 650 * _this.pixelRatio) {
								temp += chr[a];
							}else {
								a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
								row.push(temp);
								temp = "";
							}
						}
						row.push(temp); 
						if (row.length > 2) {
							let rowCut = row.slice(0, 2);
							let rowPart = rowCut[1];
							let test = "";
							let empty = [];
							for (var a = 0; a < rowPart.length; a++) {
						        if (ctx.measureText(test).width < 690 * _this.pixelRatio) {
									test += rowPart[a];
							    }else {
								    break;
							    }
							}
						   empty.push(test);
						   var group = empty[0] + "..."//这里只显示两行，超出的用...表示
						   rowCut.splice(1, 1, group);
								row = rowCut;
						}
						for (var b = 0; b < row.length; b++) {
							ctx.fillText(row[b], bannerTextX, bannerTextY + b * 50 *_this.pixelRatio, 650 * _this.pixelRatio);
						}
						
						//头像 描述
						uni.getImageInfo({
						 src:_this.headImg,
						 success(image) {
												
							// 头像和二维码大小都需要在规定大小的基础上放大像素比的比例后面都会*this.pixelRatio
							let headerW = 48 * _this.pixelRatio
							let headerX = 20 * _this.pixelRatio 
							let headerY = 20 * _this.pixelRatio + bannerH + 120 * _this.pixelRatio
							// 控制头像为圆形
							ctx.setStrokeStyle('rgba(0,0,0,.2)') //设置线条颜色，如果不设置默认是黑色，头像四周会出现黑边框
							ctx.arc(headerX + headerW / 2, headerY + headerW / 2, headerW / 2, 0, 2 * Math.PI)
							ctx.stroke()
							//画完之后执行clip()方法，否则不会出现圆形效果
							ctx.clip()
							// 将头像画到画布上			
							ctx.drawImage(image.path, headerX, headerY, headerW, headerW)
							ctx.restore()
							ctx.save()
							// console.log("uniqueCodeuniqueCode",uniqueCode)
							let invateCode = _this.user.name + ` 邀请您一起来参加`
							let invateCodeX = headerX + headerW + 14 * _this.pixelRatio
							let invateCodeY = headerY + headerW/2 + ((26*_this.pixelRatio)/2)
							ctx.setFontSize(26*_this.pixelRatio);
							ctx.setFillStyle('#333333');
							ctx.fillText(invateCode, invateCodeX, invateCodeY);
							ctx.stroke();
							
							let qrCode = _this.baseUrl + '/api/person/getQrCode?activityId='+_this.info.id + '&userId='+ _this.user.userId;
							//二维码
							uni.getImageInfo({
								src: qrCode,
								success(res){
									// 画当前页面的二维码
									const img_w = 160*_this.pixelRatio
									const img_x = _this.pupopWidth - img_w - 30 *_this.pixelRatio
									const img_y = _this.pupopHeight - img_w - 30*_this.pixelRatio				            
		                            ctx.drawImage(res.path,img_x,img_y,img_w,img_w)
									//画提示文字
									const tiptextX = 30 * _this.pixelRatio
									const tiptext1Y = img_y + (img_w/2)
									const tiptext2Y = img_y + (img_w/2) + 30 * _this.pixelRatio + 14 * _this.pixelRatio
									const tiptext1 = '长按识别二维码'
									const tiptext2 = '一起参加吧'
									ctx.setFontSize(26*_this.pixelRatio)
									ctx.setFillStyle("#979797")
									ctx.fillText(tiptext1, tiptextX, tiptext1Y);
									ctx.stroke();
									ctx.setFontSize(26*_this.pixelRatio)
									ctx.setFillStyle("#979797")
									ctx.fillText(tiptext2, tiptextX, tiptext2Y);
									ctx.stroke();
									ctx.draw(true, () => {
											uni.canvasToTempFilePath({
											width: _this.pupopWidth,
											height: _this.pupopHeight,
											destWidth: _this.pupopWidth,				              
		                                    destHeight:_this.pupopHeight,
										    canvasId: canvasId,
										    fileType: 'png',
											quality:1,
											success: function(res) {
												_this.posterImg = res.tempFilePath;//最终将canvas转换为图片
												//_this.$refs.popup.open();
												uni.hideLoading()
												_this.showCanvas = false;
											},
											fail(error) {
												toast('生成海报失败，请稍后重试！')
											    setTimeout(()=>{
												    uni.hideLoading()
													_this.showCanvas = false;
											    },2000)
											}
									    },_this)
									})
								},
								fail(error) {
									console.log('获取二维码失败',error)
									toast('生成海报失败，获取二维码失败')
									setTimeout(()=>{
											uni.hideLoading();
											_this.showCanvas = false;
									},2000)
								}
							})
						},
						fail(error) {
							toast('生成海报失败，获取头像失败')
							setTimeout(()=>{
								uni.hideLoading();
								_this.showCanvas = false;
							},2000)
													
													
						}
					});
										
				},
				fail(error) {
					toast('生成海报失败，获取详情图失败')
					setTimeout(()=>{
						uni.hideLoading();
						_this.showCanvas = false;
					},2000)		 
				}
			})
		 },
		//将图片保存到本地相册
		saveToLocal(){
			//#ifdef MP-WEIXIN
			    uni.saveImageToPhotosAlbum({
					filePath: this.posterImg,
					success: ()=>{
						toast('保存到相册成功');
						this.showShare = false;
						share({activityId:this.info.id}).then(()=>{
							
						})
					},
					fail:(err)=>{
						console.log("保存到相册失败",err)
					}
				});
		  //#endif 
		}
	}
  }
</script>


<style lang="scss" scoped>
	.share-box{
		background-color: #000000aa;
		position: fixed;
		left: 0;
		top: 0;
		height: 100%;
		width: 100%;
		z-index: 200;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		.share-card{
			// position: relative;
			// left: 30rpx;
			// top: 285rpx;
			width: 690rpx;
			height: 1050rpx;
			background: #FFFFFF;
			border-radius: 65rpx;
			.image-box{
				width: 690rpx;
				height: 640rpx;
				border-radius: 60rpx 60rpx 0 0;
				background-position: center;
				background-repeat: no-repeat;
				background-size: cover;
			}
			.content-box{
				padding: 20rpx;
				.content-title{
					font-weight: 700;
					font-size: 40rpx;
					color: #333333;
					line-height: 50rpx;
				}
				.info{
					display: flex;
					align-items: center;
					margin-top: 20rpx;
					.info-avatar{
						width: 60rpx;
						height: 60rpx;
						margin-right: 20rpx;
					}
				}
			}
			.qrcode-box{
				padding: 20rpx;
				display: flex;
				justify-content: space-between;
				// position: absolute;
				// bottom: 40rpx;
				align-items: center;
				.info{
					display: flex;
					flex-direction: column;
					justify-items: center;
					text{
						font-size: 28rpx;
						color: #979797;
						line-height: 40rpx;
					}
				}
				image{
					width: 140rpx;
					height: 140rpx;
				}
			}
		}
		.share-button-box{
			// position: absolute;
			// bottom: -104rpx;
			// left: 178rpx;
			width: 338rpx;
			height: 64rpx;
			padding-top: 40rpx;
			.button{
				width: 338rpx;
				height: 64rpx;
				background: #E70012;
				border-radius: 32rpx;
				font-size: 28rpx;
				color: #FFFFFF;
				padding: 0 28rpx;
			}
		}
	}
.background {
	background: linear-gradient(180deg,#E85142 0%,#E85142dd 25%, #F4F5F6);
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 1628rpx;
}
.title{
	position: absolute;
	top: 108rpx;
}
.logo{
	position: fixed;
	top: 176rpx;
	left: 30rpx;
	width: 236rpx;
	height: 96rpx;
}
.avatar{
	width: 198rpx;
	height: 198rpx;
	border: 6rpx solid #FFFFFF;
	border-radius: 100rpx;
	position: absolute;
	top: 268rpx;
	left: 276rpx;
	z-index: 1;
	background-color: #EDF6FF;
}
.content{
	width: 690rpx;
	height: 850rpx;
	border-radius: 60rpx;
	position: absolute;
	top: 300rpx;
	left: 30rpx;
	.image{
		width: 100%;
		height: 100%;
		border-radius: 60rpx;
	}
	.item-content{
		position: absolute;
		left: 0rpx;
		bottom: 50rpx;
		.item-box-title{
			font-weight: 700;
			font-size: 40rpx;
			color: #FFFFFF;
			padding: 0 20rpx;
			overflow: hidden;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
		}
		.item-box-content{
			font-weight: 400;
			font-size: 32rpx;
			color: #FFFFFF;
			margin-top: 14rpx;
			padding: 0 20rpx; 
			overflow: hidden;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
		}
		.item-button-box{
			margin-top: 34rpx;
			.box-button{
				width: 690rpx;
				height: 98rpx;
				z-index: 988;
			}
		}
	}
}
.button-box{
	display: flex;
	position: relative;
	top: 1190rpx;
	left: 0;
	.button{
		text-align: center;
		width: 312rpx;
		height: 100rpx;
		border-radius: 50rpx;
		font-weight: 600;
		font-size: 36rpx;
		line-height: 100rpx;
		letter-spacing: 3rpx;
		border: none;
		position: inherit;
	}
	.left{
		color: #FFFFFF;
		background: #FFD97A;
		box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(228,88,69,0.28);
	}
	.right{
		color: #E70012;
		background: #FFFFFF;
		box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(228,88,69,0.28);
	}
}
</style>